package chihane.jdaddressselector;

import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import mlxy.utils.Dev;

public class BottomDialog extends Dialog {
    private AddressSelector selector;
    private String addressinfo;
    private Context mContext;
    private OnAddressSelectedListener listener;
    public BottomDialog(Context context) {
        super(context, R.style.bottom_dialog);
        this.mContext = context;
    }

    public BottomDialog(Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
    }

    public BottomDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
        super(context, cancelable, cancelListener);
        this.mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(mContext);
    }

    private void init(Context context) {
        if (selector==null){
            if (TextUtils.isEmpty(addressinfo)){
                selector = new AddressSelector(context);
            }else {
                selector = new AddressSelector(context,addressinfo);
            }

        }
        selector.setOnAddressSelectedListener(listener);
        setContentView(selector.getView());
        Resources resources = context.getResources();
        DisplayMetrics displayMetrics = resources.getDisplayMetrics();
        int mHeightPx = displayMetrics.heightPixels;
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
//        params.height = Dev.dp2px(context, 256);
        params.height = (int) (mHeightPx*0.65);
        window.setAttributes(params);

        window.setGravity(Gravity.BOTTOM);
    }

    public void setSelector(AddressSelector selector) {
        this.selector = selector;
    }

    public AddressSelector getSelector() {
        return selector;
    }

    public void setOnAddressSelectedListener(OnAddressSelectedListener listener) {
        this.listener = listener;
    }

    public static BottomDialog show(Context context) {
        return show(context, null);
    }

    public static BottomDialog show(Context context, OnAddressSelectedListener listener) {
        BottomDialog dialog = new BottomDialog(context, R.style.bottom_dialog);
        dialog.selector.setOnAddressSelectedListener(listener);
        dialog.show();

        return dialog;
    }

    public void setAddressinfo(String addressinfo) {
        this.addressinfo = addressinfo;
    }
}
